#coding:utf-8
import datauser
import emailutil
from kcalerter.alertRule import getAlertRule, searchStartAlertRule,getAlertrulebycontentid
from kcalerter.contentCollect import getContentBytaskid,updateCollectNoflagbyArletRule
import re
from kcalerter.alerLogger import mylogg


'''
def operateandsendemail(msg,flagtype):
    querydata=datauser.queryuserlist()
    ids=''
    emails=''
    emailtitle="爬虫信息提醒"
    resultjieguo=[]
    for item in querydata:
        if item[4] is None or not item[4].strip():
            ids='%d' %item[0]
            resultu=datauser.updatebyalertType(flagtype,ids)
            sss=[ids,'',resultu]
            resultjieguo.append(sss)
        else:
            ids='%d' %item[0]
            emails=item[4].encode('utf-8')
            mailto_list=[emails]
            sendmail=emailutil.send_mail(mailto_list,emailtitle,msg)
            if sendmail==True:
                alertType="1,2"
            else:
                alertType="1"
            resultu=datauser.updatebyalertType(alertType,ids)
            sss=[ids,sendmail,resultu]
            resultjieguo.append(sss)
    return resultjieguo
'''
#查询所有用户邮箱是否需报警
def searchuseremail():
    resultquery=datauser.queryuserlist()
    idq=''
    emailq=''
    alerttypeq=''
    useremail=[]
    for item in resultquery:
        idq='%d' %item[0]
        if item[4] is None or not item[4].strip():
            emailq=''
        else:
            emailq=item[4].encode('utf-8')
        if item[5] is None or not item[5].strip():
            alerttypeq=''
        else:
            alerttypeq=item[5].encode('utf-8')
        iddd=[idq,emailq,alerttypeq]
        useremail.append(iddd)
    return useremail
#解析需要发送页面信息的用户id
def getsenduseridmsg(useridlist):
    useridstring=','
    for i in useridlist:
            userid=i[0]
            alert_type=i[2]
            if len(alert_type)>0 and '1' in alert_type:    
                print("需要发送发送页面提醒")
                useridstring=useridstring+userid+","
    return useridstring
#解析数据并发送邮件
def sendmailbyuserid(resultemailuser,emailtitle,emailmsglist):
    resultjieguo=[]
    for i in resultemailuser:
        print(i)
        emails=i[1]
        emails=emails.encode('utf-8')
        if validateEmail(emails)==True:
            mailto_list=[emails]
            inum=0;
            emailmsg=''
            flag=0
            for m in range(len(emailmsglist)):
                if inum==100:
                    emailmsgnew=emailmsg
                    emailutil.send_mail(mailto_list,emailtitle,emailmsgnew)
                    emailmsg=emailmsglist[m]+"<br/><br/>"
                    inum=0
                    flag=0         
                else:
                    if not emailmsg.strip():
                        emailmsg=emailmsglist[m]+"<br/><br/>"
                    else:
                        emailmsg=emailmsg+emailmsglist[m]+"<br/><br/>" 
                    flag=1
            if  flag==1:
                emailmsgnew=emailmsg
                emailutil.send_mail(mailto_list,emailtitle,emailmsgnew)
        ''''
        alert_type=i[2]
        if len(emails)>0 and len(alert_type)>0 and '2' in alert_type:
            emails=emails.encode('utf-8')
            mailto_list=[emails]
            
            sendmaillt=emailutil.send_mail(mailto_list,emailtitle,emailmsg)
            sss=[i[0],emails,sendmaillt]
            resultjieguo.append(sss)
        '''
    return resultjieguo
#验证邮箱是否有效
def validateEmail(email):

    if len(email) > 7:
        if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email) != None:
            return True
    return False
#查询需要报警的内容
def searchContentCollectalert():
    alerttaskid=getAlertRule()
    mylogg("need alarm table alertRule's id"+alerttaskid)
    if not alerttaskid.strip():
        newids=''
    else:
        resultgetContentBytasklist=getContentBytaskid(alerttaskid)
        AlertRule=searchStartAlertRule()
        contentid=""
        for j in resultgetContentBytasklist:
            contentcollectid=j[0]#spider_content_collect.id
            content=j[6].encode('utf-8')#spider_content_collect.text_content
            task_id=j[3]
            for k in AlertRule:
                taskidalert=k[2].encode('utf-8')
                rule_alert=k[3].encode('utf-8')
                if taskidalert is None or not taskidalert.strip():
                    if isflagalertrule(rule_alert, content)==True:
                        contentid=contentidpinjie(contentcollectid)
                        break   
                else:
                    taskidalertsz=taskidalert.split(',')
                    for l in taskidalertsz:
                        if int(l)==task_id:
                            if isflagalertrule(rule_alert, content)==True:
                                contentid=contentidpinjie(contentid,contentcollectid)
                                break
        newids=quchongcontentid(contentid)
        mylogg("need alarm table contentCollect's id"+contentid)
        updateCollectNoflagbyArletRule(alerttaskid)
    return newids

#判断是否符合报警规则  rule_alert--报警规则  content--采集的新闻内容
def isflagalertrule(rule_alert,content):
    flaghh=re.search(rule_alert,content)
    if flaghh is None:
        flagh=False
    else:
        flagh=True
    return flagh
#搜索结果id去重
def quchongcontentid(contentidstring):
    contentidsz=contentidstring.split(',')
    newids=[]
    for ida in contentidsz:
        if ida.strip()=='':
            print("weikong")
        else:
            if ida not in newids:
                newids.append(ida)
    return newids
#拼接搜索结果新闻id
def contentidpinjie(contentidnew,contentid):
    if not  contentidnew.strip():
        contentidnew=str(contentid)
    else:
        contentidnew=contentidnew+','+str(contentid)
    return contentidnew
#根据预警规则查询是否报警
def alertbyalertrule(resultreturncontentids):
    infoids=''
    for m in range(len(resultreturncontentids)):
        if not infoids.strip():
            infoids=str(resultreturncontentids[m])
        else:
            infoids=infoids+","+str(resultreturncontentids[m])
    returnAlertRule=getAlertrulebycontentid(infoids)
    web=''
    email=[]
    for lista in returnAlertRule:
        contentid=lista[0]
        if lista[1] is None or not lista[1].strip():
            contenttitle=""
        else:
            contenttitle=lista[1].encode('utf-8')
        if lista[2] is None or not lista[2].strip():
            contentcontent=""
        else:
            contentcontent=lista[2].encode('utf-8')
        if lista[3] is None or not lista[3].strip():
            contenturl=""
        else:
            contenturl=lista[3].encode('utf-8')
        ruleway=lista[4]
        if ruleway==0 or ruleway==1:
            if not web.strip():
                web=str(contentid)
            else:
                web=web+","+str(contentid)
        if ruleway==0 or ruleway==2:
            stringaaa="<span style='color: red;'>标题:</span>"+contenttitle+";&nbsp;&nbsp;&nbsp;<span style='color: red;'>内容:</span>"+contentcontent+";&nbsp;&nbsp;&nbsp;<span style='color: red;'>来源url:</span>&nbsp;&nbsp;&nbsp;"+contenturl
            email.append(stringaaa)      
    return web,email       